package com.CampusForum.community.service.impl;

import com.CampusForum.community.dao.CommentMapper;
import com.CampusForum.community.dao.DiscussPostMapper;
import com.CampusForum.community.entity.Comment;
import com.CampusForum.community.service.CommentService;
import com.CampusForum.community.util.CommunityConstant;
import com.CampusForum.community.util.CommunityUtil;
import com.CampusForum.community.util.SensitiveFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService, CommunityConstant {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private SensitiveFilter sensitiveFilter;
    @Autowired
    private DiscussPostMapper discussPostMapper;
    @Override
    public List<Comment> getComments(int entityTypePost, int id, int offset, int limit) {
        return commentMapper.getCommentsByEntity(entityTypePost, id, offset, limit);
    }

    @Override
    public int getCommentCount(int entityTypeComment, int id) {
        return commentMapper.getCountByEntity(entityTypeComment, id);
    }

    @Override
    public void insertComment(Comment comment) {
        if (comment == null) {
            log.error("comment为空");
            return;
        }
        String content = comment.getContent();
        if (content == null) {
            log.error("评论内容为空");
            return;
        }
        String html = HtmlUtils.htmlEscape(content);
        String sensitive = sensitiveFilter.filter(html);
        comment.setContent(sensitive);
        // 插入评论
        int rows = commentMapper.insertComment(comment);
        if (rows != 1) {
            log.info("插入评论失败");
        }
        // 修改帖子评论数量
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            int count = commentMapper.getCountByEntity(ENTITY_TYPE_POST
                    , comment.getEntityId());
            discussPostMapper.updateCommentCount(comment.getEntityId(), count);
        }
    }
}
